/* Controller.m:
 * You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 *
 * Written by Mai Nguyen, NeXT Developer Support
 *
 */
#import	<dbkit/dbkit.h>
#import <libc.h>
#import "Controller.h"
#import "QualifiedAssociation.h"

/* Define localized strings */
#define INSTALL_MODEL NXLocalizedString("Please install SybaseDemo.dbmodel into your ~/Library/Databases and restart.", NULL, "Notify user that SybaseDemo.dbmodel must be installed in his Databases directory.")

@implementation Controller

/* At init time, the proper association is set up between the master fetchgroup
 * and the detail fetchgroup, such that whenever a fetch happens, that fetch
 * will be done with the specified qualifier.
 */ 
-appDidInit:sender
{
	id	dbDatabase;

		/* Notify the user if the database can't be found */
	if ( (dbDatabase = [DBDatabase findDatabaseNamed:"SybaseDemo" connect:YES]) == nil) {
		NXRunAlertPanel(NULL, INSTALL_MODEL, "OK", NULL, NULL);
		return self;
	}
	[dbDatabase setDelegate:self];
	
	detailFetchGroup = [storeTable fetchGroupNamed:"sales"];

	  	/* Set up the new association.
		   Note that the new association now belongs to the DBModule
		   just as the old one did. */
        newAssociation = [[QualifiedAssociation alloc]
		initAndReplaceAssociationTo:detailFetchGroup];
	dbQualifier = [[DBQualifier alloc] 
			initForEntity:[detailFetchGroup entity]
			fromDescription: "%p > 1", "quantity"];
	[newAssociation setQualifier: dbQualifier];
	[storeTable fetchAllRecords:sender];
	[theWindow makeKeyAndOrderFront:nil];
	return self;
}

- changeQualifier:sender
{
 	if (dbQualifier)
		[dbQualifier free];
	dbQualifier = [[DBQualifier alloc] 
			initForEntity:[detailFetchGroup entity]
			fromDescription: "%p > %d", "quantity", 
			(int)[quantityField intValue]];
	[newAssociation setQualifier: dbQualifier];
	[storeTable fetchAllRecords:sender];
	return self;
}

- free
{
	if (dbQualifier)
		[dbQualifier free];
	return [super free];
}

/* For debugging purpose */
- (BOOL)db:aDb willEvaluateString:(const unsigned char*)aString
     usingBinder:aBinder
{
	fprintf(stderr, "SQL Query: %s\n", (char *)aString);
	return YES;
}
	
@end

